package com.suning.yace;

import java.nio.ByteOrder;
import java.util.List;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageEncoder;
import io.netty.util.CharsetUtil;

@Sharable
public class LiveLengthFieldPrepender extends MessageToMessageEncoder<ByteBuf> {
    
    private static final String MSG_START_FLAG = "sn";
    
    private ByteOrder byteOrder = ByteOrder.BIG_ENDIAN;
    
    @SuppressWarnings("deprecation")
	@Override
    protected void encode(ChannelHandlerContext ctx, ByteBuf msg, List<Object> out) throws Exception {
        int length = msg.readableBytes();
        out.add(ctx.alloc().buffer(1).order(byteOrder).writeBytes(MSG_START_FLAG.getBytes(CharsetUtil.UTF_8)));
        out.add(ctx.alloc().buffer(1).order(byteOrder).writeInt(length));
        out.add(msg.retain());
    }
}
